/**
 * 
 */
package com.xth8013.as.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xth8013.as.dao.MenuDao;
import com.xth8013.as.dao.RoleDao;
import com.xth8013.as.domain.Menu;
import com.xth8013.as.domain.Role;
import com.xth8013.as.exception.ServiceLogicException;
import com.xth8013.as.service.RoleService;
import com.xth8013.as.util.ObjectUtils;
import com.xth8013.as.util.RoleQueryHelper;
import com.xth8013.as.util.StringUtils;
import org.springframework.transaction.annotation.Transactional;


/**
 * 
 * @Description:
 * @author: tianhua.xie
 * @Date: 2017年2月9日 下午9:53:07 
 * 
 */
@Service("roleService")
@Transactional
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleDao roleDao;
	@Autowired
	private MenuDao menuDao;

	@Override
	public Map<String, Object> listRole(RoleQueryHelper helper) {
		
		
		if (StringUtils.isNotBlank(helper.getOrderField())) {
			if (helper.getOrderField().equals("roleName")) {
				helper.setOrderField("role_name");
			} else if (helper.getOrderField().equals("roleId")) {
				helper.setOrderField("role_id");
			}
		} else {
			helper.setOrderField("role_id");
		}

		Map<String, Object> dataMap = new HashMap<String, Object>();

		helper.setTotalRecNum(roleDao.cntRolesByHelper(helper));


		List<Role> roleList = roleDao.loadAllRolesByHelper(helper);


		dataMap.put("total", helper.getTotalRecNum());
		dataMap.put("rows", roleList);


		return dataMap;
	}

	@Override
	public List<Map<String, Object>> loadMenuTree() {

		List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
		Map<String, Object> treeNode = null;
		Map<String, Map<String, Object>> id_nodeMap = new HashMap<String, Map<String, Object>>();

		List<Menu> menuList = menuDao.loadAllMenus();

		for (Menu menu : menuList) {

			treeNode = new HashMap<String, Object>();
			treeNode.put("id", menu.getMenuId());
			treeNode.put("text", menu.getMenuName());
			if (menu.getGrade() >= 2 && menu.getIsLeaf() == 0) {
				treeNode.put("state", "closed");
			}

			id_nodeMap.put(menu.getMenuId() + "", treeNode);

			if (menu.getParentId() == 0) {
				treeList.add(treeNode);
			} else {
				// 寻找父节点
				Map<String, Object> parenNode = id_nodeMap.get(menu.getParentId() + "");
				if (parenNode != null) {
					List<Map<String, Object>> childList = null;
					if (parenNode.get("children") == null) {
						childList = new ArrayList<Map<String, Object>>();
					} else {
						childList = (List<Map<String, Object>>) parenNode.get("children");
					}
					childList.add(treeNode);
					parenNode.put("children", childList);
				}
			}
		}

		return treeList;
	}
	
	@Override
	public List<Map<String, Object>> loadRoleMenuTree(Integer roleId) {
		
		if (ObjectUtils.isBlank(roleId)) {
			throw new ServiceLogicException("角色ID不能为空");
		}
		
		List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
		Map<String, Object> treeNode = null;
		Map<String, Map<String, Object>> id_nodeMap = new HashMap<String, Map<String, Object>>();

		List<Menu> menuList = menuDao.loadAllMenus();
		List<Long> roleMenuIdList = roleDao.loadAllRoleMenuByRoleId(roleId);

		// System.out.println("roleMenuIdList = " + roleMenuIdList);

		for (Menu menu : menuList) {

			treeNode = new HashMap<String, Object>();
			treeNode.put("id", menu.getMenuId());
			treeNode.put("text", menu.getMenuName());
			if (menu.getGrade() >= 2 && menu.getIsLeaf() == 0) {
				treeNode.put("state", "closed");
			}
			// System.out.println(roleMenuIdList);
			if (ObjectUtils.isNotBlank(roleMenuIdList)) {
				if (roleMenuIdList.contains(menu.getMenuId()) && menu.getIsLeaf() == 1) {
					treeNode.put("checked", true);
					// System.out.println("==============" + menu.getMenuId());
				}
			}

			id_nodeMap.put(menu.getMenuId() + "", treeNode);

			if (menu.getParentId() == 0) {
				treeList.add(treeNode);
			} else {
				// 寻找父节点
				Map<String, Object> parenNode = id_nodeMap.get(menu.getParentId() + "");
				if (parenNode != null) {
					List<Map<String, Object>> childList = null;
					if (parenNode.get("children") == null) {
						childList = new ArrayList<Map<String, Object>>();
					} else {
						childList = (List<Map<String, Object>>) parenNode.get("children");
					}
					childList.add(treeNode);
					parenNode.put("children", childList);
				}
			}
		}

		return treeList;
	}


	@Override
	public void save(Role role, String roleMenuData) {
		Integer roleId = null;
		
		// 添加角色信息
		try {
			Role dbRole = roleDao.selectByName(role.getRoleName());
			// 已存在
			if (ObjectUtils.isNotBlank(dbRole)) {
				// 状态为删除状态
				if (dbRole.getRoleStatus().equals("0")) {
					dbRole.setRoleName(role.getRoleName());
					dbRole.setRoleRemark(role.getRoleRemark());
					dbRole.setRoleStatus("1");
					roleDao.update(dbRole);
					roleId = dbRole.getRoleId();
				} else {// 重复添加
					throw new ServiceLogicException("该角色【" + role.getRoleName() + "】已存在");
				}
			} else {// 不存在，直接插入
				// 状态：正常
				role.setRoleStatus("1");
				// 插入信息 并 获取主键值
				roleDao.insert(role);
				roleId = role.getRoleId();
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceLogicException(e.getMessage());
		}

		// System.out.println("roleId = " + roleId);

		/**
		 * 插入到角色_菜单表
		 */
		if (StringUtils.isNotBlank(roleMenuData)) {
			String[] menuIdArray = roleMenuData.split(",");

			try {
				for (String menuId : menuIdArray) {
					roleDao.insertRoleMenu(roleId, Long.parseLong(menuId));
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new ServiceLogicException("角色菜单创建失败");
			}
		}

	}

	@Override
	public Role getRoleById(Integer roleId) {
		if (ObjectUtils.isBlank(roleId)) {
			throw new ServiceLogicException("角色ID不能为空");
		}
		Role dbRole = roleDao.selectById(roleId);
		if (ObjectUtils.isBlank(dbRole)) {
			throw new ServiceLogicException("该ID[" + roleId + "]对应的角色不存在");
		}
		return dbRole;
	}

	@Override
	public void modifyRole(Role role, String roleMenuData) {

		if (ObjectUtils.isBlank(role) || ObjectUtils.isBlank(role.getRoleId())) {
			throw new ServiceLogicException("角色ID不能为空");
		}

		/**
		 * 修改角色信息
		 * 
		 */

		Role dbRole = roleDao.selectById(role.getRoleId());
		if (ObjectUtils.isBlank(dbRole)) {
			throw new ServiceLogicException("该角色【" + role.getRoleId() + "】不存在");
		}
		dbRole.setRoleName(role.getRoleName());
		dbRole.setRoleRemark(role.getRoleRemark());
		try {
			roleDao.update(dbRole);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceLogicException(e.getMessage());
		}

		/**
		 * 修改角色菜单信息（删除所有，再新增）
		 * 
		 */
		roleDao.deleteRoleMenusByRoleId(role.getRoleId());

		if (StringUtils.isNotBlank(roleMenuData)) {
			String[] menuIdArray = roleMenuData.split(",");

			try {
				for (String menuId : menuIdArray) {// 再新增
					roleDao.insertRoleMenu(role.getRoleId(), Long.parseLong(menuId));
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new ServiceLogicException("角色菜单创建失败");
			}
		}
	}

	@Override
	public void delectRoles(String decRoleIds) {

		if (StringUtils.isBlank(decRoleIds)) {
			throw new ServiceLogicException("要删除的角色ID不能为空");
		}
		
		
		List<Role> usingRoles = roleDao.selectUsingRoles(decRoleIds);
		
		// 判断是否有角色正在使用（查找出所有正在使用的角色）
		if (ObjectUtils.isNotBlank(usingRoles)) {// 若有，则抛出错误提示
			StringBuffer prompt = new StringBuffer("角色（");
			for (Role role : usingRoles) {
				prompt.append(role.getRoleName()).append("，");
			}
			prompt.deleteCharAt(prompt.length() - 1).append("）正在使用中。");
			throw new ServiceLogicException(prompt.toString());

		} else {// 若无，则删除所有
			try {
				// 清除该角色在角色菜单表的所有记录
				roleDao.deleteRoleMenusByIds(decRoleIds);
				/**
				 * 伪删除
				 */
				roleDao.deleteRolesByIds(decRoleIds);
			} catch (Exception e) {
				e.printStackTrace();
				throw new ServiceLogicException("系统错误");
			}
		}
	}

}
